﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
using System.Data.Entity;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using EntityFramework.Extensions;
namespace Webcar.Controllers
{
    
    public partial class RepairController : BaseControler
    {
        public ActionResult List()
        {
            return View();
        }

        public ActionResult ListPartialView(string id)
        {
            return PartialView();
        }
        public ActionResult Delete(string id)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑维修单);
            using (var DB = new WebcarContext())
            {
                var model = DB.RP_CAR_REPAIR_HEAD.Find(id);
                if (model != null)
                {
                    DB.RP_CAR_REPAIR_HEAD.Remove(model);
                    DB.MT_AFFAIR_HEAD.Delete(a => a.REPAIR_NO == id);
                    DB.SaveChanges();
                }
                return Success("List", "Repair", new { id = model.DEPT_CODE });
            }
            //return RedirectToAction("List", "Repair", new { id = model.DEPT_CODE });
            
        }
        [HttpGet]
        public ActionResult DeleteMaterial(string id)
        {
            using (var DB = new WebcarContext())
            {
                var item = DB.MT_AFFAIR_HEAD.Find(id);
                if (item == null)
                    throw new Exception("未找到对应的维修材料。");
                DB.MT_AFFAIR_HEAD.Remove(item);
                DB.SaveChanges();
                this.RecalcRepairFee(item.REPAIR_NO);
                return RedirectToAction("EditMaterial", "Repair", new { id = item.REPAIR_NO });
                //return EditMaterial(item.REPAIR_NO);
            }
            
        }
        [HttpGet]
        public ActionResult EditMaterial(string id)
        {
            var list = WebcarDataProvider.DB.MT_AFFAIR_HEAD.Where(a => a.REPAIR_NO == id)
                .Select(a=>new { 
                    affair_no=a.AFFAIR_NO,
                    item_name=a.ITEM_NAME,
                    item_model = a.ITEM_MODLE,
                    nums = a.NUMS,
                    unit = a.UNIT,
                    price = a.PRICE,
                    total_money = a.NUMS*a.PRICE,
                    xh=0
                }).ToList();
            return View(viewName: "EditMaterial", model: list);
        }
        public ActionResult MaterialListPartialView(string id)
        {
            var list = WebcarDataProvider.DB.MT_AFFAIR_HEAD.Where(a => a.REPAIR_NO == id)
                .Select(a => new
                {
                    affair_no = a.AFFAIR_NO,
                    item_name = a.ITEM_NAME,
                    item_model = a.ITEM_MODLE,
                    nums = a.NUMS,
                    unit = a.UNIT,
                    price = a.PRICE,
                    total_money = a.NUMS * a.PRICE,
                    xh = 0
                }).ToList();
            return PartialView(model: list);
        }

        [HttpPost]
        public ActionResult SaveMaterial(string repair_no,string edit_item_name, string edit_item_model, string edit_item_unit, int? edit_item_nums, float? edit_item_price)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑维修单);
            if (repair_no.IsNull())
            {
                ViewBag.ErrorMessage = "没有维修单号。";
                return EditMaterial(repair_no);
            }
            if (edit_item_name.IsNull())
            {
                ViewBag.ErrorMessage = "请输入部件名称。";
                return EditMaterial(repair_no);
            }
            if (edit_item_nums ==null || edit_item_price ==null)
            {
                ViewBag.ErrorMessage = "请输入数量和单价。";
                return EditMaterial(repair_no);
            }
            if (edit_item_nums <=0 || edit_item_price<=0)
            {
                ViewBag.ErrorMessage = "请输入数量和单价。";
                return EditMaterial(repair_no);
            }
            using (var DB = new WebcarContext())
            {
                MT_AFFAIR_HEAD item = new MT_AFFAIR_HEAD();
                item.AFFAIR_NO = "MT" + DB.GetSearialId();
                item.ITEM_MODLE = edit_item_model;
                item.ITEM_NAME = edit_item_name;
                item.UNIT = edit_item_unit;
                item.PRICE = (decimal)edit_item_price;
                item.NUMS = edit_item_nums;
                item.REPAIR_NO = repair_no;
                DB.MT_AFFAIR_HEAD.Add(item);
                DB.SaveChanges();
                this.RecalcRepairFee(repair_no);
            }
            return RedirectToAction("EditMaterial", "Repair", new { id = repair_no });
        }

        void RecalcRepairFee(string repairno)
        {
            string sql = @"update RP_CAR_REPAIR_HEAD set 
                sum_fee=isnull(hour_fee,0)+isnull(manage_fee,0)+isnull((select sum(isnull(nums,0)*isnull(price,0)) from MT_AFFAIR_HEAD 
                where repair_no='{0}'),0) 
                where repair_no = '{0}'";
            sql = string.Format(sql, repairno);
            WebcarDataProvider.DB.ObjectContext.ExecuteStoreCommand(sql);
        }
        [HttpGet]
        public ActionResult Edit(string id, string deptcode)
        {
            RP_CAR_REPAIR_HEAD model = null;
            if (id.IsNotNull())
            {
                model = WebcarDataProvider.DB.RP_CAR_REPAIR_HEAD.Find(id);
            }
            if (model == null)
            {
                model = new RP_CAR_REPAIR_HEAD();
                model.DEPT_CODE = deptcode;
                model.ENTER_DATE = DateTime.Now;
                model.OUT_DATE = DateTime.Now;
            }
            ViewBag.DriverName = null;
            var driver = WebcarDataProvider.DB.BS_EMP.Find(model.DRIVER);
            if (driver != null)
                ViewBag.DriverName = driver.MAN_NAME;
            return View(model: model);
        }
        [HttpPost]
        public ActionResult Edit(RP_CAR_REPAIR_HEAD model)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑维修单);
            string err = "";

            if (CheckCarModel(model, ref err) == false)
            {
                ViewBag.ErrorMessage = err;
                var driver = WebcarDataProvider.DB.BS_EMP.Find(model.DRIVER);
                if (driver != null)
                    ViewBag.DriverName = driver.MAN_NAME;
                return View(model: model);
            }

            RP_CAR_REPAIR_HEAD item = null;
            using (var DB = new WebcarContext())
            {
                if (model.REPAIR_NO.IsNotNull())
                {
                    item = DB.RP_CAR_REPAIR_HEAD.Find(model.REPAIR_NO);
                }
                else
                {
                    item = new RP_CAR_REPAIR_HEAD();
                    DB.RP_CAR_REPAIR_HEAD.Add(item);
                }
                model.CopyPropertyTo(item);
                if (item.REPAIR_NO.IsNull())
                    item.REPAIR_NO = "M" + DB.GetSearialId();
                //重新计算维修费
                //string sql = @"select sum(isnull(nums,0)*isnull(price,0)) from MT_AFFAIR_HEAD where repair_no='{0}'".FormatWith(item.REPAIR_NO);
                var list = DB.MT_AFFAIR_HEAD.Where(a => a.REPAIR_NO == item.REPAIR_NO).ToList();
                var total = DB.MT_AFFAIR_HEAD.Where(a => a.REPAIR_NO == item.REPAIR_NO).Sum(a => (a.NUMS == null ? 0 : a.NUMS) * (a.PRICE == null ? 0 : a.PRICE));
                item.SUM_FEE = (item.HOUR_FEE ?? 0) + (item.MANAGE_FEE ?? 0) + total;
                DB.SaveChanges();
            }
            return RedirectToAction("EditMaterial", "Repair", new { id = item.REPAIR_NO });
            //return Success("List", "Repair", new { id = item.DEPT_CODE });
        }

        public ActionResult Export()
        {
            GridViewSettings settings = new GridViewSettings();
            settings.Name = "gridView";
            settings.KeyFieldName = "repair_no";
            settings.Columns.Add("record_no", "牌照号");
            settings.Columns.Add("driver_name", "驾驶员");
            
            settings.AddChildDeptColumn(fieldname: "dept_code", caption: "单位（部门）");
            settings.AddChildDeptColumn(fieldname: "child_dept", caption: "详细单位");
            settings.AddRepairKindColumn();
            settings.Columns.Add("enter_date", "维修日期", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.Columns.Add("repair_dept", "维修厂");
            settings.Columns.Add("repair_cause", "维修原因");
            settings.Columns.Add("hour_fee", "工时费");
            settings.Columns.Add("manage_fee", "管理费");
            settings.Columns.Add("m_fee", "材料费");
            settings.Columns.Add("sum_fee", "费用合计");
            var data = UserDataProvider.GetRepairList(this.RouteData).ToDataTable();
            return GridViewExtension.ExportToXls(settings, data, "维修列表");
        }

        bool CheckCarModel(RP_CAR_REPAIR_HEAD model, ref string error)
        {
            if (model.DEPT_CODE.IsNull())
            {
                error = "请选择车辆单位。";
                return false;
            }
            if (model.CAR_NO.IsNull())
            {
                error = "请输入车辆牌照号。";
                return false;
            }
            if (model.DRIVER.IsNull())
            {
                error = "请输入驾驶员。";
                return false;
            }
            if (model.ENTER_DATE == null||model.OUT_DATE==null)
            {
                error = "请输入进厂日期和出厂日期。";
                return false;
            }
            if (model.ENTER_DATE >model.OUT_DATE)
            {
                error = "进厂日期不能小于出厂日期。";
                return false;
            }

            if (model.REPAIR_DEPT.IsNull())
            {
                error = "请输入承修单位。";
                return false;
            }
            if (model.REPAIR_KIND.IsNull())
            {
                error = "请输入维修类型。";
                return false;
            }
            if (model.REPAIR_CAUSE.IsNull())
            {
                error = "请输入维修原因。";
                return false;
            }
            return true;
        }
    }
}